package E2020;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

class Sender implements Runnable {

    DatagramSocket sender = null;
    DatagramPacket packet = null;
    int targetPort;

    public Sender(DatagramSocket sender, int targetPort) {
        this.sender = sender;
        this.targetPort = targetPort;
    }

    @Override
    public void run() {
        Scanner input = new Scanner(System.in);
        try {
            while (true){
                String message = input.nextLine();
                byte[] buf = message.getBytes();
                packet = new DatagramPacket(buf,0,buf.length, InetAddress.getByName("127.0.0.255"),targetPort);
                sender.send(packet);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Receiver implements Runnable {

    DatagramSocket server = null;
    DatagramPacket packet = null;

    public Receiver(DatagramSocket server) {
        this.server = server;
    }

    @Override
    public void run() {

        try {
            byte[] buf = new byte[1024];
            packet = new DatagramPacket(buf,0, buf.length);
            while (true){
                server.receive(packet);
                String str = new String(packet.getData(),0,packet.getLength());
                System.out.println(packet.getAddress()+":"+packet.getPort()+":"+str);
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if (server!=null){
                server.close();
            }
        }
    }
}
public class QQRoom {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入当前窗口：");
        int current = input.nextInt();
        System.out.println("请输入目标窗口：");
        int target = input.nextInt();

        try {
            DatagramSocket socket = new DatagramSocket(current);
            new Thread(new Sender(socket,target)).start();
            new Thread(new Receiver(socket)).start();

        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
}

